package com.jiaquyun.jcyx.main.mine

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.ClipboardUtils
import com.blankj.utilcode.util.TimeUtils
import com.jiaquyun.jcyx.R
import com.jiaquyun.jcyx.entity.UserInvoiceQuery
import com.module.lemlin.owner.OwnerAbstractActivity
import kotlinx.android.synthetic.main.activity_invoice_details.*


class InvoiceDetailsActivity : OwnerAbstractActivity() {

    companion object {
        private const val KEY_INVOICE_DETAILS = "KEY_INVOICE_DETAILS"
        fun open(details: UserInvoiceQuery) {
            val bundle = Bundle().apply {
                putSerializable(KEY_INVOICE_DETAILS, details)
            }
            ActivityUtils.startActivity(bundle, InvoiceDetailsActivity::class.java)
        }
    }

    private val mUserInvoiceQuery: UserInvoiceQuery? by lazy {
        intent?.extras?.getSerializable(KEY_INVOICE_DETAILS) as? UserInvoiceQuery
    }

    override val layoutResId: Int
        get() = R.layout.activity_invoice_details

    override fun stateBar(): StatusBar {
        return StatusBar(isLightMode = true, color = R.color.white, view = flInvoiceDetailsBar)
    }

    override fun initView() {

        ivAppBack.setOnClickListener { finish() }

        mUserInvoiceQuery?.let {
            tvInvoiceDetailsTitle.text = it.invoice_title
            tvInvoiceDetailsNo.text = it.invoice_code
            tvInvoiceDetailsPrice.text = "￥${it.invoice_money}"
            tvInvoiceDetailsTime.text = TimeUtils.millis2String(it.createtime * 1000)
        }

        tvInvoiceDetailsDianzi.setOnClickListener { view ->
            mUserInvoiceQuery?.let {
//                MineRichTextActivity.openUrl(this, title = "电子发票", url = it.pdf_url)
                openBrowser(this,it.pdf_url)
            }
        }

        tvInvoiceDetailsDizhi.setOnClickListener { view ->
            mUserInvoiceQuery?.let {
                ClipboardUtils.copyText(it.pdf_url)
                toast("复制成功，请在外部浏览器打开")
            }
        }

    }

    fun openBrowser(context: Context, url: String?) {
        val intent = Intent()
        intent.action = Intent.ACTION_VIEW
        intent.data = Uri.parse(url)
        // 注意此处的判断intent.resolveActivity()可以返回显示该Intent的Activity对应的组件名
        // 官方解释 : Name of the component implementing an activity that can display the intent
        if (intent.resolveActivity(context.getPackageManager()) != null) {
            val componentName = intent.resolveActivity(context.getPackageManager())
            context.startActivity(Intent.createChooser(intent, "请选择浏览器"))
        } else {
            toast("链接错误或无浏览器")
        }
    }
}